#!/usr/bin/python
# -*- coding: utf-8 -*-

#Author: Yuanhao Li <jay_21cn@hotmail.com>
#File: babel.py
#Usage: Client of ING from project Babel
#Copyright (C) 2007 Yuanhao Li<jay_21cn@hotmail.com>

#This program is free software; you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation; either version 2 of the License, or
#(at your option) any later version.

#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.

#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software Foundation,
#Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

#本程序是遵从 GPL 2.0 许可发布的. 你可以自由修改和再发布本程序, 
#但请遵守 GPL 2.0 条款, 尊重知识产权.

import cookielib, urllib, urllib2

from PyQt4 import QtCore
from PyQt4.QtCore import QRegExp

import ingcinfobase as Info

class Babel(QtCore.QObject):
	def __init__(self, url, usr, usrpwd, proxy):
		QtCore.QObject.__init__(self)
		self.url = url
		self.usr = usr.encode('utf-8', 'replace')
		self.usrpwd = usrpwd
		self.loginUrl = url + '/login.php'
		self.addIngUrl = url + '/recv/ing.vx'
		self.cookie = cookielib.CookieJar()
		self.proxy = proxy
		self.headers = {'User-Agent': Info.IngcUserAgent}

		if proxy != '':
			self.proxyHandler = urllib2.ProxyHandler({'http': proxy})
			self.urlOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookie), self.proxyHandler)
		else:
			self.urlOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookie))
		self.logined = False

	def getProxy(self):
		return self.proxy

	def login(self):
		try:
			values = {'usr':self.usr, 'usr_password':self.usrpwd}
			data = urllib.urlencode(values)
			request = urllib2.Request(self.loginUrl, data, self.headers)
			#request.add_header('User-Agent', 'OpenAnything/1.0 +http://diveintopython.org/')
			#request.add_header('User-Agent', Info.IngcUserAgent)
			self.urlhandler = self.urlOpener.open(request)

			if not 'babel_usr_email' in [c.name for c in self.cookie]:
				return False
			else:
				request = urllib2.Request(self.url)
				request.add_header('User-Agent', Info.IngcUserAgent)
				self.urlhandler = self.urlOpener.open(request)
				page = self.urlhandler.read(2000).decode('utf-8', 'replace')
				x = QRegExp('(<a href="/u/)(.*)(" class="tr">)(.*)(</a> <a href="/user/modify.vx" class="tr">)')
				x.indexIn(page)
				self.userNickname = x.cap(4)
				self.logined = True
				return True
		except:
			return False

	def logout(self):
		self.cookie.clear()
		self.logined = False

	def getUserNickname(self):
		return self.userNickname

	def getUrl(self):
		return self.url

	def addIng(self, ing):
		ingutf8 = ing.toUtf8()
		values = {'doing':ingutf8}
		data = urllib.urlencode(values)
		request = urllib2.Request(self.addIngUrl, data, self.headers)
		try:
			self.urlOpener.open(request)
		except:
			self.emit(QtCore.SIGNAL("AddIngTimeOut"), ing)
